<template>
  <div class="client-management-container">
    <!-- 搜索区域 -->
    <div class="bg-white p-4 rounded-t-lg">
      <div class="flex items-center justify-between">
        <div class="flex gap-2">
          <el-input
            v-model="searchParams.clientName"
            :placeholder="t('client.clientName')"
            clearable
            :prefix-icon="Search"
            @input="debouncedSearch()"
          />
          <el-button type="primary" @click="handleSearch">
            {{ t('authority.common.search') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 客户列表表格 -->
    <div class="table-container bg-white p-4 rounded shadow-sm">
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="tableData.length > 0"
        @retry="retryFetch"
      >
        <div class="table-wrapper">
          <el-table 
            :data="tableData" 
            border 
            height="100%" 
            class="adaptive-table design-table"
            table-layout="auto"
            :header-cell-style="headerCellStyle"
          >
          <!-- 数据列 - 完全自适应宽度 -->
          <el-table-column 
            prop="clientName" 
            :label="t('authority.client.clientName')" 
            min-width="120"
            class-name="data-column"
          />
          <el-table-column 
            prop="countryRegion" 
            :label="t('authority.client.countryRegion')" 
            min-width="120"
            class-name="data-column"
          />
          <el-table-column 
            prop="organizationEmail" 
            :label="t('authority.client.organizationEmail')" 
            min-width="180"
            class-name="data-column"
          />
          <el-table-column 
            prop="adminName" 
            :label="t('authority.client.adminName')" 
            min-width="120"
            class-name="data-column"
          />
          <!-- <el-table-column 
            prop="installer" 
            :label="t('authority.client.installer')" 
            min-width="120"
            class-name="data-column"
          /> -->
          <!-- <el-table-column 
            prop="installerCompany" 
            :label="t('authority.client.installerCompany')" 
            min-width="150"
            class-name="data-column"
          /> -->
          <el-table-column 
            prop="createTime" 
            :label="t('authority.client.createTime')" 
            min-width="150"
            class-name="data-column"
          />
          <el-table-column 
            prop="modifyTime" 
            :label="t('authority.client.modifyTime')" 
            min-width="150"
            class-name="data-column"
          />
          
          <!-- 操作列 - 固定宽度，始终在右侧 -->
          <el-table-column
            :label="t('authority.common.operate')"
            width="120"
            align="center"
            fixed="right"
            class-name="operation-column"
          >
            <template #default="scope">
              <div class="operation-buttons">
                <el-button 
                  link 
                  type="primary" 
                  v-if="hasPermission('sys:clients:update') || isSuperAdmin"
                  @click="handleModify(scope.row)"
                >
                  {{ t('authority.common.modify') }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50,100]"
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </PageState>
    </div>

    <!-- 客户表单对话框组件 -->
    <client-form-dialog
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :form-data="formData"
      :dialog-type="dialogType"
      @submit-success="handleDialogSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
// 客户管理页（Client Management）
// 职责：
// - 查询/分页展示客户
// - 编辑客户（弹窗）
// - 依据权限控制按钮可见性
import { ref, reactive, onMounted, defineAsyncComponent } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getClientList, updateClient } from "./data";
import { useI18n } from "@/composables/useI18n";
import { usePermission } from "@/composables/usePermission";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";

const ClientFormDialog = defineAsyncComponent(() => import("./components/ClientFormDialog.vue"));

// 多语言
const { t } = useI18n();
// 权限
const { hasPermission, isSuperAdmin } = usePermission();

// 搜索参数
const searchParams = reactive({
  clientName: ""
});

// 表格数据
const tableData = ref<any[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const errorMessage = ref("");

// 表头样式：与设计稿一致的浅灰背景
const headerCellStyle = () => ({
  background: '#F5F6FA',
  color: '#111827',
  fontWeight: 600
});

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formData = ref({});

// 初始化
onMounted(() => {
  loadTableData();
});

// 加载表格数据
const loadTableData = async () => {
  loading.value = true;
  try {
    const result = await getClientList({
      page: currentPage.value,
      limit: pageSize.value,
      clientName: searchParams.clientName
    });

    tableData.value = result.list;
    total.value = result.totalCount;
  } catch (error) {
    console.error('加载客户数据失败:', error);
    ElMessage.error('加载客户数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索：重置到第 1 页并重新加载
const handleSearch = () => {
  currentPage.value = 1;
  loadTableData();
};

// 分页：修改每页条数
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadTableData();
};

// 分页：跳转页码
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadTableData();
};


// 修改客户：打开对话框并回填数据
const handleModify = (row: any) => {
  dialogType.value = "edit";
  formData.value = { ...row };
  dialogVisible.value = true;
};

// 客户表单提交成功回调
const handleDialogSuccess = async (formData: any) => {
  try {
    if (formData.isAdd) {
      ElMessage.warning('当前仅支持修改，暂无新增接口');
      return;
    }

    const result = await updateClient({
      id: String(formData.id ?? ''),
      clientName: String(formData.clientName ?? ''),
      organizationAddress: String(formData.organizationAddress ?? ''),
      adminName: String(formData.adminName ?? ''),
      adminMobile: String(formData.adminMobile ?? '')
    });

    if (result.success) {
      ElMessage.success(result.message);
      dialogVisible.value = false;
      loadTableData();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 重试加载
const retryFetch = () => {
  errorMessage.value = "";
  loadTableData();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  handleSearch();
}, 500, { leading: false, trailing: true });
</script>

<style lang="scss" scoped>
.client-management-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-container {
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 16px;
}

/* 表格样式 - 与设计稿一致 */
.adaptive-table {
  // 设置表格布局为自动，实现完全自适应
  :deep(.el-table) {
    table-layout: auto;
    --el-table-border-color: #E5E7EB; // 全局分隔线颜色
  }
  
  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  // 表头：统一浅灰背景，深色文字，加粗，圆角
  :deep(.el-table__header-wrapper),
  :deep(.el-table__header-wrapper th),
  :deep(.el-table__header-wrapper tr),
  :deep(.el-table__header-wrapper .cell),
  :deep(.el-table__header-wrapper thead),
  :deep(.el-table__header-wrapper thead tr),
  :deep(.el-table__header-wrapper thead tr th) {
    background-color: #F5F6FA !important;
    color: #111827 !important;
    font-weight: 600;
    border-bottom: 1px solid #E5E7EB !important;
    padding: 10px 16px;
  }
  
  // 表头左右圆角
  :deep(.el-table__header-wrapper thead tr th:first-child) {
    border-top-left-radius: 8px;
  }
  :deep(.el-table__header-wrapper thead tr th:last-child) {
    border-top-right-radius: 8px;
  }
  
  // 顶部细线颜色
  :deep(.el-table__inner-wrapper::before) {
    background-color: #E5E7EB !important;
    height: 1px;
  }

  // 表体：白底，文字颜色，底部分隔线，内边距
  :deep(.el-table__body tr),
  :deep(.el-table__body td) {
    background-color: #ffffff !important;
  }
  
  :deep(.el-table__body .el-table__cell) {
    color: #374151;
    padding: 12px 16px;
    border-bottom: 1px solid #E5E7EB !important;
  }
  
  // 行 hover 效果
  :deep(.el-table__body tr:hover > td) {
    background: #F9FAFB !important;
  }
  
  // 数据列完全自适应宽度
  :deep(.data-column) {
    .cell {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: keep-all;
    }
  }
  
  // 操作列固定样式，确保始终在右侧
  :deep(.operation-column) {
    position: sticky;
    right: 0;
    z-index: 2;
    background-color: var(--el-table-bg-color);
    
    .cell {
      white-space: nowrap;
      overflow: hidden;
    }
  }
  
  // 操作按钮容器 - 链接风格
  .operation-buttons {
    display: flex;
    gap: 0;
    justify-content: center;
    align-items: center;
    flex-wrap: nowrap;
    
    .el-button {
      flex-shrink: 0;
      min-width: auto;
      padding: 0 0; // 看起来像纯文本链接
      font-size: 13px;
      color: #0F766E; // 链接主色
    }
    
    .el-button:hover {
      color: #115E59;
      text-decoration: underline;
      background: transparent;
    }
    
    // 分隔竖线
    .el-button:not(:last-child)::after {
      content: "|";
      display: inline-block;
      margin: 0 10px;
      color: #6B7280; // 更深的灰色，更容易看见
    }
  }
  
  // 确保固定列在斑马纹表格中也有正确的背景色
  :deep(.el-table__row:nth-child(even)) {
    .operation-column {
      background-color: var(--el-table-row-hover-bg-color);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .adaptive-table {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
    }
    
    .operation-buttons {
      flex-direction: column;
      gap: 4px;
      
      .el-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
